package com.jt.util;

import org.jboss.netty.handler.codec.http.CookieEncoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 张琪
 * @date 2020/12/16
 * @describe
 */
public class CookieUtil {


    /**
     * 获取对应cookieName 的 cookie
     *
     * @param request
     * @param cookieName
     * @return 指定的cookie
     */
    public static Cookie getCookie(HttpServletRequest request, String cookieName) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if (cookieName.equals(cookie.getName())) {
                    return cookie;
                }
            }
        }
        return null;
    }

    /**
     * 获取cookie的值
     *
     * @param request
     * @param cookieName
     * @return
     */
    public static String getCookieValue(HttpServletRequest request, String cookieName) {
        Cookie cookie = CookieUtil.getCookie(request, cookieName);
        return cookie == null ? null : cookie.getName();
    }

    /**
     * 向响应中添加cookie
     *
     * @param response
     * @param cookieName
     * @param cookieValue
     * @param path
     * @param domain
     * @param seconds
     */
    public static void addCookie(HttpServletResponse response, String cookieName, String cookieValue,
                                 String path, String domain, Integer seconds) {
        Cookie cookie = new Cookie(cookieName, cookieValue);
        cookie.setPath(path);
        cookie.setDomain(domain);
        cookie.setMaxAge(seconds);
        response.addCookie(cookie);
    }

    public static void addCookie(HttpServletResponse response, String cookieName) {
        Cookie cookie = new Cookie(cookieName, "");
        cookie.setPath("/");
        cookie.setDomain("jt.com");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
    }

}
